import React, { useCallback } from 'react';
import { ChevronUpIcon, ChevronDownIcon } from 'tdesign-icons-react';
import styles from './index.module.less';

export interface SortableColumnProps {
  label: string;
  sortKey: string;
  onSort: (sortKey: string, sortOrder: 'asc' | 'desc' | null) => void;
  currentSortKey?: string;
  currentSortOrder?: 'asc' | 'desc' | null;
  className?: string;
  align?: 'left' | 'center' | 'right';
}

const SortableColumn: React.FC<SortableColumnProps> = ({
  label,
  sortKey,
  onSort,
  currentSortKey,
  currentSortOrder,
  className = '',
  align = 'center',
}) => {
  const isActive = currentSortKey === sortKey;
  
  const handleUpClick = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
    // 修复：ChevronUpIcon 应该设置为升序（小到大）
    const newSortOrder = (isActive && currentSortOrder === 'asc') ? null : 'asc';
    onSort(sortKey, newSortOrder);
  }, [isActive, currentSortOrder, sortKey, onSort]);

  const handleDownClick = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
    // 修复：ChevronDownIcon 应该设置为降序（大到小）
    const newSortOrder = (isActive && currentSortOrder === 'desc') ? null : 'desc';
    onSort(sortKey, newSortOrder);
  }, [isActive, currentSortOrder, sortKey, onSort]);

  const getSortIcon = () => {
    const isAscActive = currentSortOrder === 'asc';
    const isDescActive = currentSortOrder === 'desc';
    
    return (
      <div className={styles.sortIcons}>
        <ChevronUpIcon 
          className={`${styles.sortIcon} ${styles.sortIconUp} ${isAscActive ? styles.sortIconActive : ''}`}
          onClick={handleUpClick}
        />
        <ChevronDownIcon 
          className={`${styles.sortIcon} ${styles.sortIconDown} ${isDescActive ? styles.sortIconActive : ''}`}
          onClick={handleDownClick}
        />
      </div>
    );
  };

  const getAlignClass = () => {
    switch (align) {
      case 'left':
        return styles.sortableColumnLeft;
      case 'right':
        return styles.sortableColumnRight;
      case 'center':
      default:
        return styles.sortableColumnCenter;
    }
  };

  return (
    <div 
      className={`${styles.sortableColumn} ${getAlignClass()} ${className} ${isActive && currentSortOrder ? styles.sortableColumnActive : ''}`}
      tabIndex={0}
      role="button"
      aria-label={`按 ${label} 排序`}
    >
      <span className={styles.sortableColumnLabel}>{label}</span>
      {getSortIcon()}
    </div>
  );
};

export default SortableColumn;
